<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编号" prop="projectId">
        <el-input
          v-model="queryParams.projectId"
          placeholder="请输入项目编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="creationTime">
        <el-date-picker clearable
          v-model="queryParams.creationTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          :disabled="multiple"
          @click="handleAdd"
          v-hasPermi="['count:countproject:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['count:countproject:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['count:countproject:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['count:countproject:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="countprojectList" 
      @selection-change="handleSelectionChange"
      show-summary
      :summary-method="getSummaries"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="项目编号" align="center" prop="projectId" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="成本价 (元)" align="center" prop="costPrice" />
      <el-table-column label="零售价(元)" align="center" prop="retailPrice" />
  
      <el-table-column label="成本总价(元)" align="center">
        <template #default="scope">
          <!-- 假设数量为 1，可根据实际情况修改 -->
          <span>{{ (scope.row.costPrice * 1).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="零售总价(元)" align="center">
        <template #default="scope">
          <!-- 假设数量为 1，可根据实际情况修改 -->
          <span>{{ (scope.row.retailPrice * 1).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="利润(元)" align="center">
        <template #default="scope">
          <span>{{ (scope.row.retailPrice - scope.row.costPrice).toFixed(2) }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column label="项目类别" align="center" prop="projectCategory">
        <template #default="scope">
          <dict-tag :options="sys_project_category" :value="scope.row.projectCategory"/>
        </template>
      </el-table-column>
      <el-table-column label="发票项目" align="center" prop="invoiceItem">
        <template #default="scope">
          <dict-tag :options="sys_qnvoice_item" :value="scope.row.invoiceItem"/>
        </template>
      </el-table-column>
      <el-table-column label="单位 (字典)" align="center" prop="unit">
        <template #default="scope">
          <dict-tag :options="sys_unit_ci" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="creationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['count:countproject:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['count:countproject:remove']">删除</el-button>
        </template>
      </el-table-column> -->
      
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改检查项目设置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="countprojectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目编号" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目编号" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="零售价(元)" prop="retailPrice">
          <el-input v-model="form.retailPrice" placeholder="请输入零售价(元)" />
        </el-form-item>
        <el-form-item label="成本价 (元)" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入成本价 (元)" />
        </el-form-item>
        <el-form-item label="创建时间" prop="creationTime">
          <el-date-picker clearable
            v-model="form.creationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="项目类别" prop="projectCategory">
          <el-input v-model="form.projectCategory" placeholder="请输入项目类别" />
        </el-form-item>
        <el-form-item label="发票项目" prop="invoiceItem">
          <el-input v-model="form.invoiceItem" placeholder="请输入发票项目" />
        </el-form-item>
        <el-form-item label="项目状态" prop="projectStatus">
          <el-radio-group v-model="form.projectStatus">
            <el-radio
              v-for="dict in sys_project_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="会员折扣" prop="memberDiscount">
          <el-input v-model="form.memberDiscount" placeholder="请输入会员折扣" />
        </el-form-item>
        <el-form-item label="单位 (字典)" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位 (字典)" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Countproject">
import { listCountproject, getCountproject, delCountproject, addCountproject, updateCountproject } from "@/api/count/countproject";



const { proxy } = getCurrentInstance();

// 字典数据
const { 
  sys_project_status,
  sys_project_category,
  sys_qnvoice_item,
  sys_member_discount,
  sys_unit_ci 
} = proxy.useDict(
  'sys_project_status',
  'sys_project_category',
  'sys_qnvoice_item',
  'sys_member_discount',
  'sys_unit_ci'
);
// 监听字典数据变化
watch(sys_qnvoice_item, (newVal) => {
  console.log('发票项目字典数据:', newVal);
}, { immediate: true });

const countprojectList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: null,
    projectName: null,
    creationTime: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询检查项目设置列表 */
function getList() {
  // loading.value = true;
  //   const params = {
  //   ...queryParams.value,
  //   projectStatus: queryParams.value.projectStatus === '' ? null : queryParams.value.projectStatus
  // };
  listCountproject(queryParams).then(response => {
    countprojectList.value = response.rows;
    console.log(countprojectList.value)
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: null,
    projectName: null,
    retailPrice: null,
    costPrice: null,
    creationTime: null,
    remarks: null,
    projectCategory: null,
    invoiceItem: null,
    projectStatus: null,
    memberDiscount: null,
    unit: null
  };
  proxy.resetForm("countprojectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加检查项目设置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCountproject(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改检查项目设置";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["countprojectRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCountproject(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCountproject(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除检查项目设置编号为"' + _ids + '"的数据项？').then(function() {
    return delCountproject(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('count/countproject/export', {
    ...queryParams.value
  }, `countproject_${new Date().getTime()}.xlsx`)
}
// 在组件挂载时获取字典数据
onMounted(() => {
  getList();
  // 检查字典数据是否正确加载
  console.log('所有字典数据:', {
    sys_project_status,
    sys_project_category,
    sys_qnvoice_item,
    sys_member_discount,
    sys_unit_ci
  });
});

// 定义计算合计的方法
const getSummaries = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (column.label === '成本总价(元)') {
      const values = data.map(item => Number(item.costPrice));
      const sum = values.reduce((prev, curr) => prev + curr, 0);
      sums[index] = sum.toFixed(2);
    } else if (column.label === '零售总价(元)') {
      const values = data.map(item => Number(item.retailPrice));
      const sum = values.reduce((prev, curr) => prev + curr, 0);
      sums[index] = sum.toFixed(2);
    } else if (column.label === '利润(元)') {
      const values = data.map(item => Number(item.retailPrice) - Number(item.costPrice));
      const sum = values.reduce((prev, curr) => prev + curr, 0);
      sums[index] = sum.toFixed(2);
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

</script>
